<template>
  <textarea :id="tinymceId" :value="value" />
</template>

<script>
import axios from 'axios';
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver';
import 'tinymce/plugins/image';
import 'tinymce/plugins/media';
import 'tinymce/plugins/table';
import 'tinymce/plugins/link';
import 'tinymce/plugins/code';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/contextmenu';
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/colorpicker';
import 'tinymce/plugins/textcolor';
import 'tinymce/plugins/preview';
import 'tinymce/plugins/fullscreen';
import 'tinymce/plugins/charmap';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/hr';
import 'tinymce/plugins/searchreplace';
import 'tinymce/plugins/insertdatetime';
import 'tinymce/plugins/toc';
import 'tinymce/plugins/codesample';
import 'tinymce/plugins/print';

export default {
  name: 'Tinymce',
  props: {
    value: {
      type: String,
      required: true
    },
    action: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: 'image/jpg, image/jpeg, image/png, image/gif'
    },
    maxSize: {
      type: Number,
      default: 2097152
    },
    height: {
      type: Number,
      default: 300
    }
  },
  data() {
    return {
      tinymceId: 'editor-' + new Date().getMilliseconds(),
      DefaultInit: {
        language_url: window.publicPath + 'tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: window.publicPath + 'tinymce/skins/ui/oxide',
        content_css: window.publicPath + 'tinymce/skins/content/default/content.css',
        height: this.height,
        menubar: false,
        theme: 'silver',
        browser_spellcheck: true,
        branding: false,
        statusbar: false,
        elementpath: false,
        paste_data_images: true
      },
      toolbar: [
        'formatselect | fontsizeselect | bold italic underline strikethrough blockquote | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist toc codeformat blockformats ',
        'outdent indent | codesample charmap hr insertdatetime pastetext | lists image media table link unlink | code searchreplace print fullscreen preview | removeformat undo redo '
      ],
      plugins: 'lists image media table wordcount code print fullscreen preview codesample toc insertdatetime searchreplace link charmap paste hr'
    };
  },
  watch: {
    value: function(val) {
      if (tinymce.activeEditor.getContent() !== val) {
        tinymce.activeEditor.setContent(val);
      }
    }
  },
  beforeDestroy: function() {
    tinymce.get(this.tinymceId).destroy();
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      const self = this;
      if (self.disabled) {
        tinymce.init({
          // 挂载的DOM对象
          selector: `#${self.tinymceId}`,
          // 默认配置
          ...self.DefaultInit,
          readonly: 1
        });
        return;
      }
      tinymce.init({
        // 挂载的DOM对象
        selector: `#${self.tinymceId}`,
        // 默认配置
        ...self.DefaultInit,
        toolbar: self.toolbar,
        plugins: self.plugins,
        init_instance_callback: function(editor) {
          editor.on('input change undo redo', () => {
            self.$emit('on-click', editor.getContent());
          })
        },
        // 图片上传
        images_upload_handler: function(blobInfo, success, failure) {
          if (blobInfo.blob().size > self.maxSize) {
            failure('上传图片太大，上传失败!');
          } else {
            if (self.accept.indexOf(blobInfo.blob().type) >= 0) {
              if (self.action === '') {
                failure('未设置上传路径！');
                return;
              }
              const formData = new FormData();
              formData.append('file', blobInfo.blob());
              axios.post(`${window.apiPath}${self.action}`, formData).then(response => {
                if (response.data.code === 0) {
                  success(response.data.content.url);
                } else {
                  failure('上传失败！');
                }
              });
            } else {
              failure('图片格式错误!');
            }
          }
        }
      });
    }
  }
};
</script>
